package com.chuangjiangx.member.basic.web.controller;

import com.chuangjiangx.commons.CurrentThreadContext;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.commons.sms.SMSUtils;
import com.chuangjiangx.member.basic.ddd.application.MbrSmsApplication;
import com.chuangjiangx.member.basic.ddd.application.MemberApplication;
import com.chuangjiangx.member.basic.ddd.application.command.ModifyMemberCommand;
import com.chuangjiangx.member.basic.ddd.application.command.ModifyMobileCommand;
import com.chuangjiangx.member.score.dao.model.InMbrScoreGrandTotalRule;
import com.chuangjiangx.member.basic.web.interceptor.Login;
import com.chuangjiangx.member.basic.web.request.CheckPhone;
import com.chuangjiangx.member.basic.web.request.UpdateMemberRequest;
import com.chuangjiangx.member.basic.web.request.UpdatePhoneRequest;
import com.chuangjiangx.member.basic.web.response.MemberInfoResponse;
import com.chuangjiangx.member.score.web.response.PlusScoreRuleDetailForH5Response;
import com.chuangjiangx.member.common.utils.BeanUtils;
import com.chuangjiangx.member.coupon.ddd.query.MbrCardQuery;
import com.chuangjiangx.member.score.ddd.query.MbrScoreGrandTotalRuleQuery;
import com.chuangjiangx.member.basic.ddd.query.MemberQuery;
import com.chuangjiangx.member.basic.ddd.query.dto.MemberDTO;
import com.chuangjiangx.member.basic.ddd.query.dto.MemberDetailDTO;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrSourceTerminal;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 会员管理
 */
@Slf4j
@RestController
@RequestMapping(value = "/h5/member", produces = "application/json")
public class MemberController extends BaseController {

    @Value("${member.h5.domain}")
    private String h5Domian;
    @Autowired
    private MemberApplication memberApplication;
    @Autowired
    private MemberQuery memberQuery;
    @Autowired
    private MbrCardQuery mbrCardQuery;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MbrScoreGrandTotalRuleQuery mbrScoreGrandTotalRuleQuery;
    @Autowired
    private MbrSmsApplication mbrSmsApplication;

    /**
     * 修改会员信息
     *
     * @param updateMember 会员信息
     * @return com.chuangjiangx.commons.response.UnderlineResponse
     */
    @RequestMapping(value = "/update-member")
    @ResponseBody
    @Login
    public Response updateMember(@Validated @RequestBody UpdateMemberRequest updateMember, HttpServletRequest request) throws Exception {

        MbrUserContext userContext = (MbrUserContext) CurrentThreadContext.getCurrentUser();

        //更新的会员信息
        ModifyMemberCommand modifyMemberCommand = new ModifyMemberCommand(
                updateMember.getMemberId(),
                updateMember.getName(),
                updateMember.getSex(),
                updateMember.getBirthday(),
                userContext.getMerchantId(),
                //终端类型设置成H5**********
                MbrSourceTerminal.H5_TERMINAL.value,
                userContext.getMerchantUserId()
        );
        modifyMemberCommand.setHeadimgurl(updateMember.getHeadimgurl());
        //更新操作
        memberApplication.modifyMember(modifyMemberCommand);
        return ResponseUtils.success();
    }

    /**
     * 修改会员手机号码
     *
     * @param updatePhoneRequest 请求参数
     * @return com.chuangjiangx.commons.response.UnderlineResponse
     */
    @RequestMapping(value = "/update-member-phone")
    @ResponseBody
    @Login
    public Response updatePhoneNumber(@Validated @RequestBody UpdatePhoneRequest updatePhoneRequest, HttpServletRequest request) throws Exception {

        // 校验短信验证码是否正确
        SMSUtils.codeCheck(updatePhoneRequest.getMobile(), updatePhoneRequest.getVerifyCode(), redisTemplate);

        MbrUserContext userContext = (MbrUserContext) CurrentThreadContext.getCurrentUser();

        //修改的会员手机号码信息
        ModifyMobileCommand modifyMobileCommand = new ModifyMobileCommand(
                updatePhoneRequest.getMemberId(),
                updatePhoneRequest.getMobile(),
                userContext.getMerchantId(),
                MbrSourceTerminal.H5_TERMINAL.value,
                //终端类型设置成H5**********
                userContext.getMerchantUserId()
        );
        memberApplication.modifyMobile(modifyMobileCommand);
        return ResponseUtils.success();
    }

    /**
     * 查询会员信息
     *
     * @return com.chuangjiangx.commons.response.UnderlineResponse
     * @see MemberInfoResponse
     */
    @RequestMapping(value = "/search-member-info")
    @ResponseBody
    @Login
    public Response searchMemberDetailByPhone(HttpServletRequest request) throws Exception {

        MbrUserContext userContext = loginService.currentUserContext();

        MemberInfoResponse memberInfoResponse = new MemberInfoResponse();
        MemberDetailDTO memberH5DTO = memberQuery.searchMemberDetailById(userContext.getMemberId());
        MemberDTO memberDTO = memberQuery.queryByMemberId(userContext.getMemberId());
        String wxCardId = mbrCardQuery.searchWxCardId(userContext.getMerchantId());
        //对象转换
        BeanUtils.convertBean(memberH5DTO, memberInfoResponse);
        memberInfoResponse.setH5Domain(h5Domian);
        memberInfoResponse.setWxCardId(wxCardId);
        memberInfoResponse.setHasFace(StringUtils.isNotBlank(memberDTO.getFaceId()));
        memberInfoResponse.setFaceImg(userContext.getAiFaceImg());
        return ResponseUtils.success(memberInfoResponse);
    }

    /**
     * 根据手机号码，发送验证码(用于注册，修改手机号码)
     *
     * @param checkPhone 手机号码
     * @return com.chuangjiangx.commons.response.UnderlineResponse
     */
    @RequestMapping(value = "/send-code")
    @ResponseBody
    public Response sendMobleCodeforRegister(@Validated @RequestBody CheckPhone checkPhone) throws Exception {
//        String code = SMSUtils.sendCodeInfo(checkPhone.getMobile(), redisTemplate);
//        CodeMsg codeMsg = new CodeMsg(code);
//        log.info("手机:{},验证码:{}",checkPhone.getMobile(),code);
//        loginService.pushRongLianSMS(checkPhone.getMobile(), 2, codeMsg, code);//推送模板
//        SMSUtils.saveCodeInfo(checkPhone.getMobile(), code, redisTemplate);//保存验证码到redis
        String code = mbrSmsApplication.sendMobileVerifyCode(checkPhone.getMobile());
        return ResponseUtils.success(code);
    }

    /**
     * 根据商户id查询积分累计规则
     *
     * @return com.chuangjiangx.commons.response.UnderlineResponse
     * @see PlusScoreRuleDetailForH5Response
     */
    @RequestMapping(value = "/search-score-plus-rule")
    @ResponseBody
    @Login
    public Response searchScorePlusRule(HttpServletRequest request) throws Exception {

        MbrUserContext userContext = (MbrUserContext) CurrentThreadContext.getCurrentUser();

        InMbrScoreGrandTotalRule rule = mbrScoreGrandTotalRuleQuery.queryScoreGrandTotalRuleByMerchantId(userContext.getMerchantId());
        PlusScoreRuleDetailForH5Response response = new PlusScoreRuleDetailForH5Response();
        BeanUtils.convertBean(rule, response);
        return ResponseUtils.success(response);
    }

}
